#include "ulink.h"

/*创建链表*/
link_t *link_creat(void)
{
	link_t *L = (link_t *)malloc(sizeof(link_t));
	if(NULL==L){
		return L;	
	}

	memset(L,0,sizeof(link_t));
	L->next = NULL;
	return L;
}

/*增加数据*/
int insert_data(link_t *L,const char *ID,int fd)
{
	link_t *p = link_creat();
	if(NULL==p){
		return -1;
	}
	
	strcpy(p->ID,ID);
	p->fd = fd;
	p->next = NULL;

	p->next = L->next;
	L->next = p;

	return 0;
}

/*根据ID查找*/
int find_data(link_t *L,const char *ID)
{
	link_t *p = L->next;
	while(p){
		if(0==strcmp(p->ID,ID)){
			return 0;
		}
		p = p->next;
	}

	return -1;

}

/*根据fd删除*/
int delete_data(link_t *L,int fd)
{
	link_t *p = L;
	while(p->next){
		if(p->next->fd==fd){
			link_t *q = p->next;
			p->next = q->next;
			free(q);
			return 0;
		}
		p = p->next;
	}
	return -1;
}

/*释放链表*/
int free_link(link_t **L)
{
	link_t *q = *L;
	while(q){
		q = (*L)->next;
		free(*L);
		(*L) = q;
	}

	*L = NULL;

	return 0;
}